import requests


from datetime import datetime, timedelta

class AccessTokenFetcher:

    def __init__(self, memory_config):
        self.access_token = None
        self.last_update = None
        self.baidu_llm_config = memory_config.config  # 从MemoryConfig中提取baidu_llm_config

    def get_access_token(self):
        # 如果accessToken==None或者上次更新时间距离现在超过一个小时，则重新获取
        if self.access_token is None or self.last_update is None \
                or datetime.now() - self.last_update > timedelta(hours=1):

            url = "https://aip.baidubce.com/oauth/2.0/token"
            params = {
                'grant_type': 'client_credentials',
                'client_id': self.baidu_llm_config.get("api_key"),  # 使用api_key属性
                'client_secret': self.baidu_llm_config.get("secret_key")  # 使用secret_key属性
            }
            response = requests.post(url, data=params)
            self.access_token = response.json()['access_token']
            self.last_update = datetime.now()

        return self.access_token